﻿<%@ WebHandler Language="C#" Class="ApsPlanConfirmHandler" %>

using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Collections;
using Newtonsoft.Json;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Net;

//Description: 排产计划确认（转工、检验、外委、BOM、工装）处理程序
//Copyright (c) : 通力凯顿（北京）系统集成有限公司
//Writer:zhangrj
//create Date:2022-07-11
public class ApsPlanConfirmHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    uLMSCommonBusiness commonBusiness = new uLMSCommonBusiness();
    ApsPlanConfirmBusiness apsPlanConfirm = new ApsPlanConfirmBusiness();
    ApsPlanDownSendBusiness apsPlanDownSend = new ApsPlanDownSendBusiness();
    RbContainerBusiness rbBusiness = new RbContainerBusiness();
    string rbFactoryID = System.Configuration.ConfigurationManager.AppSettings["RBFactoryID"].ToString(); //热表ID
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            var action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "登录过期，请重新登录" }));
                return;
            }
            switch (action)
            {
                case "InitPageData": //初始化页面数据
                    InitPageData(context);
                    break;
                case "GetApsPlanDatasByPage": //获取排产计划确认列表数据（分页）
                    GetApsPlanDatasByPage(context);
                    break;
                case "GetBomAndGZDatas": //获取BOM和工装列表数据
                    GetBomAndGZDatas(context);
                    break;
                case "GetApsFeedBackByPage": //获取排产反馈列表数据（分页）
                    GetApsFeedBackByPage(context);
                    break;
                case "SaveApsPlanConfirmDatas": //保存排产计划确认
                    SaveApsPlanConfirmDatas(context);
                    break;
                /*----------------转工排产确认-------------------------*/
                case "GetApsPlanShipReceiveDatasByPage": //获取转工排产计划接收列表数据（分页）
                    GetApsPlanShipReceiveDatasByPage(context);
                    break;
                case "GetApsPlanShipOutDatas": //获取转工排产计划转出列表数据（分页）
                    GetApsPlanShipOutDatas(context);
                    break;
                case "ApsPlanShipConfirmVaild": //转工确认验证
                    ApsPlanShipConfirmVaild(context);
                    break;
                case "SaveApsPlanShipConfirmDatas": //保存转工排产计划确认（计划转出）
                    SaveApsPlanShipConfirmDatas(context);
                    break;
                case "SaveApsPlanShipFeedDatas": //保存转工排产计划反馈日期
                    SaveApsPlanShipFeedDatas(context);
                    break;
                case "SaveApsPlanShipReceiveDatas": //保存转工排产计划接收数据并下发手动排产
                    SaveApsPlanShipReceiveDatas(context);
                    break;
                case "SaveApsPlanDetailData": //保存排产详细数据
                    SaveApsPlanDetailData(context);
                    break;
                case "CancelApsPlanShipReceiveDatas": //撤销转工排产计划接收数据
                    CancelApsPlanShipReceiveDatas(context);
                    break;
                case "exportReceive"://转工计划接收--导出
                    exportReceive(context);
                    break;
                /*----------------热表转工无限制名单-------------------------*/
                case "GetRBApsShipDatas": //获取转工排产计划数据且没有添加到无限制的（转热表的）
                    GetRBApsShipDatas(context);
                    break;
                case "SaveApsShipUnlimitedDatas": //保存转工排产无限制名单
                    SaveApsShipUnlimitedDatas(context);
                    break;
                case "GetRBUnLimitApsDatas": //获取无限制名单
                    GetRBUnLimitApsDatas(context);
                    break;
                case "ExportUnLimitToExcel": //导出无限制名单
                    ExportUnLimitToExcel(context);
                    break;
                default:
                    context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "不存在该功能" }));
                    break;
            }
        }
        catch (Exception ex)
        {
            uMESProcessResult result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    /// <summary>
    /// 导出无限制名单
    /// </summary>
    /// <param name="context"></param>
    public void ExportUnLimitToExcel(HttpContext context)
    {
        StringBuilder sql = new StringBuilder();
        sql.AppendLine(@"SELECT c.containername,wb.workflowname || ':' || w.workflowrevision workflowinfo,
                        ap.workflowstepname,ap.starttime,ap.endtime,a.createtime,a.Remark,e.fullname
                        FROM ApsUnLimitedInfo a
                        LEFT JOIN apsplandetail ap ON ap.apsplandetailid = a.apsplandetailid
                        LEFT JOIN workflowstep ws ON ws.workflowstepid = ap.workflowstepid
                        LEFT JOIN workflow w ON w.workflowid = ws.workflowid
                        LEFT JOIN workflowbase wb ON wb.workflowbaseid = w.workflowbaseid
                        LEFT JOIN containercurrentinfo c ON c.containerid = ap.containerid
                        LEFT JOIN employee e ON e.employeeid = a.createby
                        WHERE c.containerstatus = 1 AND ap.isuse = 0 AND a.status = 0");
        if (!string.IsNullOrWhiteSpace(context.Request["startDate"].ToString()))
        {
            DateTime startDate = DateTime.Parse(context.Request["startDate"].ToString() + " 00:00:00");
            sql.AppendFormat(" AND a.createtime >= to_date('{0}','yyyy-mm-dd hh24:mi:ss')", startDate);
        }
        if (!string.IsNullOrWhiteSpace(context.Request["endDate"].ToString()))
        {
            DateTime endDate = DateTime.Parse(context.Request["endDate"].ToString() + " 23:59:59");
            sql.AppendFormat(" AND a.createtime <= to_date('{0}','yyyy-mm-dd hh24:mi:ss')", endDate);
        }
        sql.AppendLine(" ORDER BY a.createtime desc,c.containerid,ws.sequence");
        DataTable dtUl = DatabaseHelper.Query_ReturnDatTable(sql.ToString());
        foreach (DataColumn item in dtUl.Columns)
        {
            switch (item.ColumnName)
            {
                case "CONTAINERNAME":
                    item.ColumnName = "批次"; break;
                case "WORKFLOWSTEPNAME":
                    item.ColumnName = "工序"; break;
                case "STARTTIME":
                    item.ColumnName = "开始日期"; break;
                case "ENDTIME":
                    item.ColumnName = "结束日期"; break;
                case "WORKFLOWINFO":
                    item.ColumnName = "工艺信息"; break;
                case "CREATETIME":
                    item.ColumnName = "添加限制时间"; break;
                case "REMARK":
                    item.ColumnName = "备注"; break;
                case "FULLNAME":
                    item.ColumnName = "操作人"; break;
                default:
                    break;
            }
        }
        dtUl.AcceptChanges();
        byte[] bytes = uLMS_CommonFunction.DataTableExportToExcel(dtUl);
        context.Response.Clear();
        context.Response.Buffer = true;
        context.Response.ClearHeaders();
        context.Response.ClearContent();
        context.Response.ContentType = "application/vnd.ms-excel";
        context.Response.AddHeader("fileDownload", "1");
        context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}{1}.xls", context.Server.UrlEncode("无限制名单导出记录"), DateTime.Now.ToString("yyyyMMddHHmmssffff")));
        context.Response.AddHeader("Content-Length", bytes.Length.ToString());
        context.Response.AddHeader("Content-Type", "UTF-8");
        context.Response.Charset = "UTF-8";
        context.Response.ContentEncoding = Encoding.UTF8;
        context.Response.BinaryWrite(bytes);
        context.Response.Flush();
        context.Response.Close();
    }

    /// <summary>
    /// 获取无限制排产计划数据（热表）
    /// </summary>
    /// <param name="context"></param>
    public void GetRBUnLimitApsDatas(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        StringBuilder sql = new StringBuilder();
        sql.AppendLine(@"SELECT c.containername,wb.workflowname || ':' || w.workflowrevision workflowinfo,a.apsunlimitedinfoid,
                        ap.workflowstepname,ap.workflowstepid,ap.starttime,ap.endtime,ap.apsplandetailid,a.createtime,a.Remark,e.fullname
                        FROM ApsUnLimitedInfo a
                        LEFT JOIN apsplandetail ap ON ap.apsplandetailid = a.apsplandetailid
                        LEFT JOIN workflowstep ws ON ws.workflowstepid = ap.workflowstepid
                        LEFT JOIN workflow w ON w.workflowid = ws.workflowid
                        LEFT JOIN workflowbase wb ON wb.workflowbaseid = w.workflowbaseid
                        LEFT JOIN containercurrentinfo c ON c.containerid = ap.containerid
                        LEFT JOIN employee e ON e.employeeid = a.createby
                        WHERE c.containerstatus = 1 AND ap.isuse = 0 AND a.status = 0 AND c.isinstore != 1");
        if (!string.IsNullOrWhiteSpace(context.Request["startDate"].ToString()))
        {
            DateTime startDate = DateTime.Parse(context.Request["startDate"].ToString() + " 00:00:00");
            sql.AppendFormat(" AND a.createtime >= to_date('{0}','yyyy-mm-dd hh24:mi:ss')", startDate);
        }
        if (!string.IsNullOrWhiteSpace(context.Request["endDate"].ToString()))
        {
            DateTime endDate = DateTime.Parse(context.Request["endDate"].ToString() + " 23:59:59");
            sql.AppendFormat(" AND a.createtime <= to_date('{0}','yyyy-mm-dd hh24:mi:ss')", endDate);
        }
        sql.AppendLine(" ORDER BY a.createtime desc,c.containerid,ws.sequence");
        uMESPagingDataDTO pageDto = new uMESPagingDataDTO();
        pageDto.CurrentPageIndex = int.Parse(context.Request["pageIndex"].ToString());
        pageDto.PageSize = int.Parse(context.Request["pageSize"].ToString());
        pageDto.strSQL = sql.ToString();
        result = DatabaseHelper.RunProcedureForPage(pageDto);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取转工排产计划数据且没有添加到无限制的（转热表的）
    /// </summary>
    /// <param name="context"></param>
    public void GetRBApsShipDatas(HttpContext context)
    {
        string containerName = context.Request["containerName"].ToString();
        StringBuilder sql = new StringBuilder();
        sql.AppendFormat(@"SELECT c.containername,ap.workflowstepname,ap.workflowstepid,ap.starttime,ap.endtime,ap.apsplandetailid,
                        wb.workflowname || ':' || w.workflowrevision workflowinfo
                        FROM apsplaninfo ai
                        LEFT JOIN apsplandetail ap ON ai.apsplaninfoid = ap.apsplaninfoid
                        LEFT JOIN workflowstep ws ON ws.workflowstepid = ap.workflowstepid
                        LEFT JOIN workflow w ON w.workflowid = ws.workflowid
                        LEFT JOIN workflowbase wb ON wb.workflowbaseid = w.workflowbaseid
                        LEFT JOIN containercurrentinfo c ON c.containerid = ai.containerid
                        WHERE ap.specfactoryid = '{0}' AND c.originalfactoryid <> '{0}' 
                        AND c.containerstatus  = 1 AND ai.isuse = 0 AND ap.isuse = 0
                        AND NOT EXISTS(SELECT 1 FROM ApsUnLimitedInfo a WHERE a.apsplandetailid = ap.apsplandetailid AND a.status = 0)", rbFactoryID);
        if (!string.IsNullOrWhiteSpace(containerName))
        {
            sql.AppendFormat(" AND c.containername = '{0}'", containerName);
        }
        sql.AppendLine(" ORDER BY c.containerid,ws.sequence");
        uMESPagingDataDTO pageDto = new uMESPagingDataDTO();
        pageDto.CurrentPageIndex = int.Parse(context.Request["pageIndex"].ToString());
        pageDto.PageSize = int.Parse(context.Request["pageSize"].ToString());
        pageDto.strSQL = sql.ToString();
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(pageDto);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存转工排产无限制名单
    /// </summary>
    /// <param name="context"></param>
    public void SaveApsShipUnlimitedDatas(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        DataTable dtAps = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        ArrayList sqlList = new ArrayList();
        StringBuilder sqlBd = new StringBuilder();
        /*获取当前操作电脑的ipv4地址，并记录到备注里*/
        //IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName());
        //IPAddress ip = host.AddressList.FirstOrDefault(p => p.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);//获取ipv4地址
        string[] ipList = { "20.12.115.39", "20.12.115.142", "20.12.115.89", "20.12.115.116", "20.12.115.95", "20.12.115.122", "20.12.186.10", "20.12.115.178", "20.12.115.97", "127.0.0.1", "::1" };//固定IP地址（后两位是本地地址，用于本地调试）
        if (!ipList.Contains(context.Request.UserHostAddress))
        {
            result.Result = false; result.Message = "当前用户地址不匹配，无法添加！";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        foreach (DataRow drAps in dtAps.Rows)
        {
            string sql = string.Format("SELECT 1 FROM ApsUnLimitedInfo a WHERE a.apsplandetailid = '{0}' AND a.status = 0", drAps["apsplandetailid"].ToString());
            if (DatabaseHelper.GetSingle(sql) != null)
            {
                result.Result = false; result.Message = string.Format("批次：{0}的工序：{1}已添加到无限制名单", drAps["containername"].ToString(), drAps["workflowstepname"].ToString());
                break;
            }
            sqlBd.AppendLine(@"INSERT INTO ApsUnLimitedInfo(ApsUnLimitedInfoID,ApsplandetailID,Createtime,Createby,Status,Remark) VALUES(");
            sqlBd.AppendFormat("'{0}',", Guid.NewGuid().ToString());
            sqlBd.AppendFormat("'{0}',", drAps["apsplandetailid"].ToString());
            sqlBd.AppendLine("sysdate,");
            sqlBd.AppendFormat("'{0}',", m_UserInfo.EmployeeID);
            sqlBd.AppendFormat("0,'操作电脑IP：{0}')", context.Request.UserHostAddress);
            sqlList.Add(sqlBd.ToString());
        }
        if (result.Result)
        {
            DatabaseHelper.ExecuteSqlTran(sqlList);
            result.Message = "保存成功";
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存排产详细数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveApsPlanDetailData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        Dictionary<string, string> param = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["param"].ToString());
        DataTable dtApsPlanDetail = JsonConvert.DeserializeObject<DataTable>(context.Request["apsPlanDetailDatas"].ToString());
        if (dtApsPlanDetail.Rows.Count == 0)
        {
            result.Result = false; result.Message = "缓存过期，请重新查询";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (string.IsNullOrWhiteSpace(param["startDate"]) || string.IsNullOrWhiteSpace(param["endDate"]))
        {
            result.Result = false; result.Message = "请填写完整数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }

        if (DateTime.Parse(param["startDate"]) > DateTime.Parse(param["endDate"]))
        {
            result.Result = false; result.Message = "排产开始日期大于结束日期";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //if (DateTime.Parse(param["startDate"]) < DateTime.Now.AddDays(3))
        //{
        //    result.Result = false; result.Message = "排产开始日期修改需超过当前时间的三天之后";
        //    context.Response.Write(JsonConvert.SerializeObject(result));
        //    return;
        //}
        string apsPlanDetailIDs = string.Empty;
        string sql = string.Empty;
        foreach (DataRow drAps in dtApsPlanDetail.Rows)
        {
            sql = string.Format(@"SELECT ap.containerid,s.specno,ws.workflowstepname,ap.specfactoryid FROM apsplandetail ap
                                LEFT JOIN workflowstep ws ON ws.workflowstepid = ap.workflowstepid
                                LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
                                LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
                                WHERE ap.apsplandetailid = '{0}'", drAps["apsPlanDetailID"].ToString());
            DataTable dtSpec = DatabaseHelper.Query_ReturnDatTable(sql);
            sql = string.Format(@" SELECT 1 FROM containershiprecord csr 
                                LEFT JOIN containershiprecordstep csdd ON csdd.containershiprecordid = csr.containershiprecordid
                                LEFT JOIN workflowstep ws ON ws.workflowstepid = csdd.workflowstepid
                                LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
                                LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
                                WHERE csr.containerid = '{0}' AND csr.isuse = 0 AND s.specno = '{1}' AND csr.senddate IS NOT NULL", dtSpec.Rows[0]["containerid"].ToString(), dtSpec.Rows[0]["specno"].ToString());
            if (DatabaseHelper.GetSingle(sql) != null)
            {
                result.Result = false; result.Message = string.Format("批次：{0}的工序：{1}已转工转出，无法修改", drAps["containerName"].ToString(), dtSpec.Rows[0]["workflowstepname"].ToString());
                break;
            }
            if (dtSpec.Rows[0]["specfactoryid"].ToString() == rbFactoryID && DateTime.Parse(param["startDate"]) < DateTime.Now.AddDays(3))
            {
                result.Result = false; result.Message = string.Format("批次：{0}的工序：{1}开始日期必须为三天之后", drAps["containerName"].ToString(), dtSpec.Rows[0]["workflowstepname"].ToString());
                break;
            }
            apsPlanDetailIDs += string.Format("'{0}',", drAps["apsPlanDetailID"].ToString());
        }
        if (!result.Result)
        {
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        apsPlanDetailIDs = apsPlanDetailIDs.TrimEnd(',');
        //查询是否已下发或者已接受
        sql = string.Format("SELECT nvl(apd.status,0) status,apd.specfactoryid FROM apsplandetail apd WHERE apd.apsplandetailid IN ({0})", apsPlanDetailIDs);
        DataTable dtRes = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtRes.AsEnumerable().Where(p => p["status"].ToString() != "0" && p["status"].ToString() != "2" && p["status"].ToString() != "4").Count() > 0)
        {
            result.Result = false; result.Message = "排产数据已接收或已删除，请重新查询";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //排产开始日期需超过三天后，只控制热表
        if (dtRes.AsEnumerable().Where(p => p["specfactoryid"].ToString() == rbFactoryID).Count() > 0 && DateTime.Parse(param["startDate"]) < DateTime.Now.AddDays(3))
        {
            result.Result = false; result.Message = "排产开始日期修改需超过当前时间的三天之后";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //更新排产基础数据
        sql = string.Format(@"UPDATE apsplandetail apd
                            SET apd.starttime = to_date('{0}','yyyy-MM-dd HH24:mi:ss'),
                            apd.endtime = to_date('{1}','yyyy-MM-dd HH24:mi:ss')
                            WHERE apd.apsplandetailid IN ({2})", param["startDate"], param["endDate"], apsPlanDetailIDs);
        DatabaseHelper.ExecuteSql(sql);
        result = apsPlanDownSend.SendHandApsDatasByShipReceive(apsPlanDetailIDs);//更新数据到看板
        result.Message = result.Result ? "更改成功" : string.Format("更新排产数据成功！{0}", result.Message);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 初始化数据
    /// </summary>
    /// <param name="context"></param>
    public void InitPageData(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        //获取工厂
        Dictionary<string, string> dic = new Dictionary<string, string>();
        DataTable dtMainFactory = commonBusiness.GetFactory(dic);
        dtMainFactory.TableName = "dtMainFactory";
        result.DBDataSet.Tables.Add(dtMainFactory);
        //获取工区
        DataTable dtWorkCenter = commonBusiness.GetWorkCenterByFacoryID(m_UserInfo.FactoryID, false);
        dtWorkCenter.TableName = "dtWorkCenter";
        result.DBDataSet.Tables.Add(dtWorkCenter);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 获取排产计划确认列表（分页）
    /// </summary>
    /// <param name="context"></param>
    public void GetApsPlanDatasByPage(HttpContext context)
    {
        string type = context.Request["type"].ToString();
        if (string.IsNullOrWhiteSpace(type))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "未知功能" }));
            return;
        }
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        DataRow dr = dt.Rows[0];
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("ScanContainerName", dr["scanContainer"].ToString());//扫描批次号
        if (!string.IsNullOrWhiteSpace(dic["ScanContainerName"].ToString()))
        {
            dic["ScanContainerName"] = commonBusiness.ContainerScan(dic["ScanContainerName"].ToString());
        }
        dic.Add("ScanOrderName", dr["scanOrder"].ToString());//扫描订单号
        dic.Add("ContainerName", dr["containerName"].ToString());//批次号
        //dic.Add("MainFactoryId", dr["mainFactory"].ToString());//主制分厂
        dic.Add("MainFactoryId", m_UserInfo.FactoryID);
        dic.Add("WorkCenterId", dr["workCenterID"].ToString());//工区
        dic.Add("AssisFactoryId", dr["assistFactory"].ToString());//承制分厂
        dic.Add("Type", type);//功能分类
        dic.Add("Status", dr["status"].ToString());//状态（0：未下发，1：下发，2：确认）
        dic.Add("PageIndex", context.Request["pageNumber"].ToString());//
        dic.Add("PageSize", context.Request["pageSize"].ToString());//
        uMESProcessResult result = apsPlanConfirm.GetApsPlanDatasByPage(dic);
        if (type == "3") //如果是外委，清空承制分厂
        {
            foreach (DataRow item in result.DBTable.Rows)
            {
                item["ASSISFACTORYNAME"] = "";
            }
            result.DBTable.AcceptChanges();
        }

        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取转工排产计划确认列表（分页）
    /// </summary>
    /// <param name="context"></param>
    public void GetApsPlanShipOutDatas(HttpContext context)
    {
        Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        string[] status = { "0", "2", "3" };//可显示的状态
        if (!status.Contains(dic["status"]))
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "不存在该状态" }));
            return;
        }
        if (!string.IsNullOrWhiteSpace(dic["scanContainer"]))
        {
            dic["scanContainer"] = commonBusiness.ContainerScan(dic["scanContainer"]);
        }
        //
        if (!string.IsNullOrWhiteSpace(dic["planStartDate"]))
        {
            dic["planStartDate"] = dic["planStartDate"] + " 00:00:00";
        }
        if (!string.IsNullOrWhiteSpace(dic["planEndDate"]))
        {
            dic["planEndDate"] = dic["planEndDate"] + " 23:59:59";
        }
        //
        if (!string.IsNullOrWhiteSpace(dic["shipStartDate"]))
        {
            dic["shipStartDate"] = dic["shipStartDate"] + " 00:00:00";
        }
        if (!string.IsNullOrWhiteSpace(dic["shipEndDate"]))
        {
            dic["shipEndDate"] = dic["shipEndDate"] + " 23:59:59";
        }
        dic.Add("MainFactoryId", m_UserInfo.FactoryID);
        uMESProcessResult result = apsPlanConfirm.GetApsPlanShipOutDatasByPage(dic);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取转工排产计划接收列表（分页）
    /// </summary>
    /// <param name="context"></param>
    public void GetApsPlanShipReceiveDatasByPage(HttpContext context)
    {
        Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        if (!string.IsNullOrWhiteSpace(dic["ScanContainerName"]))
        {
            dic["ScanContainerName"] = commonBusiness.ContainerScan(dic["ScanContainerName"]);
        }
        if (!string.IsNullOrWhiteSpace(dic["PlanStartDate"]))
        {
            dic["PlanStartDate"] = dic["PlanStartDate"] + " 00:00:00";
        }
        if (!string.IsNullOrWhiteSpace(dic["PlanEndDate"]))
        {
            dic["PlanEndDate"] = dic["PlanEndDate"] + " 23:59:59";
        }
        dic.Add("FactoryID", m_UserInfo.FactoryID);
        dic.Add("isPage", "true");
        uMESProcessResult result = apsPlanConfirm.GetApsPlanShipReceivedDatas(dic);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 验证是否有效的转工排产转出
    /// </summary>
    /// <param name="context"></param>
    public void ApsPlanShipConfirmVaild(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["datas"].ToString());
        ApsShipConfirm shipConfirm = IsVaildShipConfirmData(dt);//验证数据
        if (shipConfirm.Result && !shipConfirm.IsOtherRev) //如果验证正确，且没有其他版本，则直接保存
        {
            result = SaveApsPlanShipConfirmDatas(shipConfirm);//保存确认
            result.ReturnData = false;//不存在其他版本
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        result.Result = shipConfirm.Result;
        result.Message = shipConfirm.Message;
        result.ReturnData = shipConfirm.IsOtherRev;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存转工排产计划转出确认数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveApsPlanShipConfirmDatas(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult();
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["datas"].ToString());
        ApsShipConfirm shipConfirm = IsVaildShipConfirmData(dt);//验证数据
        if (!shipConfirm.Result)
        {
            result.Result = shipConfirm.Result; result.Message = shipConfirm.Message;
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        result = SaveApsPlanShipConfirmDatas(shipConfirm);//保存确认数据
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存转工工序转出确认数据
    /// </summary>
    /// <param name="shipConfirm"></param>
    private uMESProcessResult SaveApsPlanShipConfirmDatas(ApsShipConfirm shipConfirm)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        try
        {
            //发送到看板
            shipConfirm.SqlList.AddRange(apsPlanDownSend.SendHandApsDatasByShipOut(shipConfirm.ApsPlanDetailIDs, m_UserInfo));
            //更新状态
            shipConfirm.SqlList.Add(string.Format(@"update apsplandetail ap SET ap.confirmempid = '{0}',ap.confirmdate = sysdate,ap.status = '2',ap.lastchangedate = sysdate
                              WHERE ap.apsplandetailid IN ({1})", m_UserInfo.EmployeeID, shipConfirm.ApsPlanDetailIDs));
            //全部执行
            DatabaseHelper.ExecuteSqlTran(shipConfirm.SqlList);
            result.Message = "确认成功";
            return result;
        }
        catch (Exception e)
        {
            result.Result = false; result.Message = "报错出错：" + e.Message;
            return result;
        }
    }

    /// <summary>
    /// 验证转工排产确认数据
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    private ApsShipConfirm IsVaildShipConfirmData(DataTable dt)
    {
        ApsShipConfirm shipConfirm = new ApsShipConfirm();
        string strsql = string.Empty;
        if (dt.Rows.Count == 0)
        {
            shipConfirm.Result = false; shipConfirm.Message = "请选择待转出数据";
            return shipConfirm;
        }
        foreach (DataRow dr in dt.Rows)
        {
            if (dr["assisFactoryName"].ToString().Contains("热表")) //验证热表分厂的转工序
            {
                strsql = string.Format("SELECT 1 FROM workflowstep w WHERE w.workflowstepid = '{0}' AND w.wipmsglabel = '子工艺'", dr["WorkflowStepID"].ToString());
                if (DatabaseHelper.Query_ReturnDatTable(strsql).Rows.Count == 0)
                {
                    shipConfirm.Result = false;
                    shipConfirm.Message = string.Format("批次：{0}的转工工序：{1}没有定义【子工艺】标识", dr["ContainerName"].ToString(), dr["WorkflowStepName"].ToString());
                    break;
                }
            }
            //验证是否存在多个版本一起转出
            if (dt.Select(string.Format("ContainerID = '{0}' AND SpecNo = '{1}'", dr["ContainerID"].ToString(), dr["SpecNo"].ToString())).Length > 1)
            {
                shipConfirm.Result = false;
                shipConfirm.Message = string.Format("批次：{0}的工序：{1}存在多版，请选择一条转出", dr["ContainerName"].ToString(), dr["SpecNo"].ToString());
                break;
            }
            //验证是否已确认
            strsql = string.Format("select apd.starttime,nvl(apd.status,'0') status,apd.specfactoryid from apsplandetail apd where apd.apsplandetailid = '{0}'", dr["apsPlanDetailId"].ToString());
            DataTable dtDetail = DatabaseHelper.Query_ReturnDatTable(strsql);
            if (dtDetail.Rows.Count == 0)
            {
                shipConfirm.Result = false;
                shipConfirm.Message = string.Format("批次：{0}的工序：{1}排产记录无存在，请重新查询", dr["ContainerName"].ToString(), dr["SpecNo"].ToString());
                break;
            }
            if (dtDetail.Rows[0]["status"].ToString() != "0")
            {
                shipConfirm.Result = false; shipConfirm.Message = "存在已确认的数据，请重新查询";
                break;
            }
            if (dtDetail.Rows[0]["specfactoryid"].ToString() == rbFactoryID && DateTime.Parse(dtDetail.Rows[0]["starttime"].ToString()) < DateTime.Now.AddDays(3))
            {
                shipConfirm.Result = false;
                shipConfirm.Message = string.Format("批次：{0}的工序（热表）：{1}的排产开始时间未超过三天，无法转出确认", dr["ContainerName"].ToString(), dr["SpecNo"].ToString());
                break;
            }
            //验证是否存在其他版本
            Tuple<bool, string, ArrayList> res = IsExistOtherRevApsData(dr);
            if (!res.Item1)
            {
                shipConfirm.Result = false; shipConfirm.Message = res.Item2;
                break;
            }
            if (res.Item3.Count > 0)
            {
                shipConfirm.SqlList.AddRange(res.Item3);//追加sql
                shipConfirm.IsOtherRev = true;
            }
            shipConfirm.ApsPlanDetailIDs += string.Format("'{0}',", dr["apsPlanDetailId"].ToString());//拼接排产明细ID
        }
        shipConfirm.ApsPlanDetailIDs = shipConfirm.ApsPlanDetailIDs.TrimEnd(',');
        return shipConfirm;
    }

    /// <summary>
    /// 验证是否存在其他版本
    /// </summary>
    /// <param name="dr"></param>
    /// <returns></returns>
    private Tuple<bool, string, ArrayList> IsExistOtherRevApsData(DataRow dr)
    {
        bool res = true;//返回值
        string msg = string.Empty;//返回消息
        ArrayList sqlList = new ArrayList();
        //验证是否存在其他版本
        string strsql = @"SELECT ws.workflowstepid,ws.WorkflowStepName,nvl(ap.status,0) status,ap.apsplandetailid FROM apsplandetail ap
                       LEFT JOIN apsplaninfo ai ON ai.apsplaninfoid = ap.apsplaninfoid
                       LEFT JOIN workflowstep ws ON ws.workflowstepid = ap.workflowstepid
                       LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
                       LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
                       WHERE ap.isuse = 0 AND ai.isuse = 0 AND ai.containerid = '{0}' AND ap.workflowstepid <> '{1}' AND s.specno = '{2}'";
        strsql = string.Format(strsql, dr["ContainerID"].ToString(), dr["WorkflowStepID"].ToString(), dr["SpecNo"].ToString());
        DataTable dtRes = DatabaseHelper.Query_ReturnDatTable(strsql);
        if (dtRes.Rows.Count > 0)
        {
            if (dtRes.AsEnumerable().Where(p => p["status"].ToString() == "1").Count() > 0)
            {
                res = false; msg = string.Format("批次：{0}的转工工序：{1}在其他版本已下发派工", dr["ContainerName"].ToString(), dr["WorkflowStepName"].ToString());
            }
            foreach (DataRow item in dtRes.Rows)
            {
                if (rbBusiness.IsExistsSubContainer(dr["ContainerID"].ToString(), item["WorkflowStepName"].ToString()))//验证是否存在子卡
                {
                    res = false; msg = string.Format("批次：{0}的转工工序：{1}在其他版本已创建了子批次", dr["ContainerName"].ToString(), dr["WorkflowStepName"].ToString());
                    break;
                }
                sqlList.Add(string.Format("delete from apsplandetail apd WHERE apd.apsplandetailid = '{0}'", item["apsplandetailid"].ToString()));
                sqlList.Add(string.Format("delete from apsplandetailemp ape WHERE ape.apsplandetailid = '{0}'", item["apsplandetailid"].ToString()));
                sqlList.Add(string.Format("delete from apsplandetailemptime apt WHERE apt.apsplandetailempid IN (SELECT ape.apsplandetailempid FROM apsplandetailemp ape WHERE ape.apsplandetailid = '{0}')", item["apsplandetailid"].ToString()));
            }
        }
        return new Tuple<bool, string, ArrayList>(res, msg, sqlList);
    }

    /// <summary>
    /// 保存转工排产计划反馈日期数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveApsPlanShipFeedDatas(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        Dictionary<string, string> dic = new Dictionary<string, string>();
        string apsPlanDetailID = context.Request["apsPlanDetailID"].ToString();
        string shipPlanStartDate = context.Request["shipPlanStartDate"].ToString();
        string shipPlanEndDate = context.Request["shipPlanEndDate"].ToString();
        if (string.IsNullOrWhiteSpace(shipPlanStartDate) || string.IsNullOrWhiteSpace(shipPlanEndDate))
        {
            result.Result = false; result.Message = "未填写日期";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        if (Convert.ToDateTime(shipPlanStartDate) > Convert.ToDateTime(shipPlanEndDate))
        {
            result.Result = false; result.Message = "反馈开始日期大于结束日期";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        //查询是否过期
        string sql = string.Format("SELECT 1 FROM apsplandetail apd WHERE apd.apsplandetailid = '{0}' and (apd.status = '2' or apd.status = '4')", apsPlanDetailID);
        if (DatabaseHelper.GetSingle(sql) == null)
        {
            result.Result = false; result.Message = "数据过期，请重新查询";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        ExcuteEntity exuteEntity = new ExcuteEntity("apsplandetail", ExcuteEntity.ExcuteTypeEnum.update);
        exuteEntity.WhereFileds = new List<FieldEntity>() { new FieldEntity("apsplandetailid", apsPlanDetailID, FieldEntity.FieldTypeEnum.Str) };
        List<FieldEntity> excuteFieldList = new List<FieldEntity>();
        excuteFieldList.Add(new FieldEntity("shiprecplanstartdate", shipPlanStartDate, FieldEntity.FieldTypeEnum.DateTime));
        excuteFieldList.Add(new FieldEntity("shiprecplanenddate", shipPlanEndDate, FieldEntity.FieldTypeEnum.DateTime));
        excuteFieldList.Add(new FieldEntity("shipreceiveempid", m_UserInfo.EmployeeID, FieldEntity.FieldTypeEnum.Str));
        excuteFieldList.Add(new FieldEntity("shipreceivedate", DateTime.Now.ToString(), FieldEntity.FieldTypeEnum.DateTime));
        excuteFieldList.Add(new FieldEntity("lastchangedate", DateTime.Now.ToString(), FieldEntity.FieldTypeEnum.DateTime));
        exuteEntity.ExcuteFileds = excuteFieldList;
        result.Result = DatabaseHelper.ExecuteDataByEntity(exuteEntity);
        result.Message = result.Result ? "保存成功" : "保存失败";
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private enum ShipReceiveEnum { 主制分厂 = 0, 承制分厂 = 1 }
    /// <summary>
    /// 保存转工接收数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveApsPlanShipReceiveDatas(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        ShipReceiveEnum em = (ShipReceiveEnum)int.Parse(context.Request["type"].ToString());
        DataTable dtAps = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (dtAps.Rows.Count == 0)
        {
            result.Result = false; result.Message = "未选择数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        string apsPlanDetailIDs = string.Empty;
        dtAps.AsEnumerable().ToList().ForEach(p =>
        {
            apsPlanDetailIDs += string.Format("'{0}',", p["apsPlanDetailID"].ToString());
        });
        apsPlanDetailIDs = apsPlanDetailIDs.TrimEnd(',');
        string sql = string.Format("SELECT apd.shiprecplanstartdate,apd.shiprecplanenddate,nvl(apd.status,0) status FROM apsplandetail apd WHERE apd.apsplandetailid IN ({0})", apsPlanDetailIDs);
        DataTable dtRes = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtRes.AsEnumerable().Where(p => p["status"].ToString() != "2" && p["status"].ToString() != "4").Count() > 0)
        {
            result.Result = false; result.Message = "数据过期，请重新查询";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        switch (em)
        {
            case ShipReceiveEnum.主制分厂: //如果是主制分厂接收，则反馈日期不能为空
                if (dtRes.AsEnumerable().Where(p => string.IsNullOrWhiteSpace(p["shiprecplanstartdate"].ToString()) || string.IsNullOrWhiteSpace(p["shiprecplanenddate"].ToString())).Count() > 0)
                {
                    result.Result = false; result.Message = "不存在反馈日期，请重新查询";
                    break;
                }
                sql = string.Format("UPDATE apsplandetail apd SET apd.lastchangedate = to_date('{0}','yyyy/mm/dd hh24:mi:ss'), apd.status = '3' WHERE apd.apsplandetailid IN ({1})", DateTime.Now.ToString(), apsPlanDetailIDs);
                BusinessRule.Common.LogHelp.WriteOrcale("转工排产反馈确认" + "@^" + "排产ID：" + apsPlanDetailIDs + "主制分厂反馈确认" + "@^" + string.Format("反馈确认人：{0},反馈确认时间：{1}", m_UserInfo.EmployeeID, DateTime.Now.ToString()) + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + m_UserInfo.FullName); // 写入数据库   
                break;
            case ShipReceiveEnum.承制分厂: //如果是承制分厂接收，则反馈日期为空
                if (dtRes.AsEnumerable().Where(p => !string.IsNullOrWhiteSpace(p["shiprecplanstartdate"].ToString()) || !string.IsNullOrWhiteSpace(p["shiprecplanenddate"].ToString())).Count() > 0)
                {
                    result.Result = false; result.Message = "存在反馈日期，需主制分厂确认";
                    break;
                }
                sql = string.Format("UPDATE apsplandetail apd SET apd.shipreceiveempid = '{0}', apd.shipreceivedate = to_date('{1}','yyyy/mm/dd'),apd.lastchangedate = to_date('{2}','yyyy/mm/dd hh24:mi:ss'), apd.status = '3' WHERE apd.apsplandetailid IN ({3})", m_UserInfo.EmployeeID, DateTime.Now.ToShortDateString(), DateTime.Now.ToString(), apsPlanDetailIDs);
                break;
            default:
                result.Result = false; result.Message = "未知功能，请刷新页面";
                break;
        }
        if (!result.Result)
        {
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        DatabaseHelper.ExecuteSql(sql);
        //发送到看板
        //result = apsPlanDownSend.SendHandApsDatasByShipReceive(apsPlanDetailIDs);
        if (!result.Result)
        {
            switch (em)
            {
                case ShipReceiveEnum.主制分厂:
                    sql = string.Format("UPDATE apsplandetail apd SET apd.status = '2' WHERE apd.apsplandetailid IN ({0})", apsPlanDetailIDs);
                    break;
                case ShipReceiveEnum.承制分厂:
                    sql = string.Format("UPDATE apsplandetail apd SET apd.shipreceiveempid = null, apd.shipreceivedate = null, apd.status = '2' WHERE apd.apsplandetailid IN ({0})", apsPlanDetailIDs);
                    break;
                default:
                    break;
            }
            DatabaseHelper.ExecuteSql(sql);
        }
        else
        {
            result.Message = "操作成功";
            if (em == ShipReceiveEnum.承制分厂 && m_UserInfo.Factory.Contains("热表"))
            {
                result = rbBusiness.SaveApsShipStartContainer(apsPlanDetailIDs, m_UserInfo);
                result.Message = string.Format("转工排产接收成功！ {0}", result.Message);
            }
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 撤销转工接收数据
    /// </summary>
    /// <param name="context"></param>
    public void CancelApsPlanShipReceiveDatas(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "撤销成功" };
        DataTable dtAps = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        if (dtAps.Rows.Count == 0)
        {
            result.Result = false; result.Message = "未选择数据";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        string apsPlanDetailIDs = string.Empty;
        dtAps.AsEnumerable().ToList().ForEach(p =>
        {
            apsPlanDetailIDs += string.Format("'{0}',", p["apsPlanDetailID"].ToString());
        });
        apsPlanDetailIDs = apsPlanDetailIDs.TrimEnd(',');
        string sql = string.Format("SELECT apd.shiprecplanstartdate,apd.shiprecplanenddate,nvl(apd.status,0) status FROM apsplandetail apd WHERE apd.apsplandetailid IN ({0})", apsPlanDetailIDs);
        DataTable dtRes = DatabaseHelper.Query_ReturnDatTable(sql);
        if (dtRes.AsEnumerable().Where(p => p["status"].ToString() != "3").Count() > 0)
        {
            result.Result = false; result.Message = "数据过期，请重新查询";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        sql = string.Format("UPDATE apsplandetail apd SET apd.shipreceiveempid = null, apd.shipreceivedate = null, apd.status = '4', apd.lastchangedate = to_date('{0}','yyyy/mm/dd hh24:mi:ss') WHERE apd.apsplandetailid IN ({1})", DateTime.Now.ToString(), apsPlanDetailIDs);
        DatabaseHelper.ExecuteSql(sql);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存排产计划确认数据
    /// </summary>
    /// <param name="context"></param>
    public void SaveApsPlanConfirmDatas(HttpContext context)
    {
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["datas"].ToString());
        if (dt.Rows.Count == 0)
        {
            context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "没有需要保存的数据" }));
            return;
        }
        uMESProcessResult result = apsPlanConfirm.SaveApsPlanConfirmDatas(m_UserInfo.EmployeeID.ToString(), dt);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取BOM、工装数据
    /// </summary>
    /// <param name="context"></param>
    public void GetBomAndGZDatas(HttpContext context)
    {
        //DataSet ds = new DataSet();
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        Dictionary<string, string> dic = new Dictionary<string, string>();
        string type = context.Request["type"].ToString();
        if (type == "4")
        {
            //查询BOM数据
            dic.Add("WorkflowID", context.Request["workflowId"].ToString());//工艺ID
            dic.Add("SpecID", context.Request["specId"].ToString());//工序ID
            DataTable dtBom = apsPlanConfirm.GetApsPlanContainerBom(dic);
            dtBom.TableName = "dtBom";
            result.DBTable = dtBom;
            //ds.Tables.Add(dtBom);
        }
        else
        {
            //查询工装数据
            dic.Clear();
            dic.Add("WorkflowStepID", context.Request["workflowStepId"].ToString());//工序ID
            DataTable dtGz = apsPlanConfirm.GetApsPlanTools(dic);
            dtGz.TableName = "dtGz";
            result.DBTable = dtGz;
            //ds.Tables.Add(dtGz);
        }
        //result.DBDataSet = ds;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取排产反馈数据列表（分页）
    /// </summary>
    /// <param name="context"></param>
    public void GetApsFeedBackByPage(HttpContext context)
    {
        DataTable dt = JsonConvert.DeserializeObject<DataTable>(context.Request["params"].ToString());
        DataRow dr = dt.Rows[0];
        Dictionary<string, string> dic = new Dictionary<string, string>();
        dic.Add("mfgOrderName", dr["mfgOrderName"].ToString());//件号
        dic.Add("containerName", dr["containerName"].ToString());//批次号
        dic.Add("productName", dr["productName"].ToString());//件号
        dic.Add("startTime", dr["startTime"].ToString());//开始时间
        dic.Add("endTime", dr["endTime"].ToString());//结束时间
        dic.Add("factory", m_UserInfo.FactoryID);//分厂
        dic.Add("PageIndex", context.Request["pageNumber"].ToString());//
        dic.Add("PageSize", context.Request["pageSize"].ToString());//
        uMESProcessResult result = apsPlanConfirm.GetApsFeedBackByPage(dic);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    private class ApsShipConfirm
    {
        public ApsShipConfirm()
        {
            this.Result = true;
            this.Message = string.Empty;
            this.SqlList = new ArrayList();
            this.ApsPlanDetailIDs = string.Empty;
            this.IsOtherRev = false;
        }
        /// <summary>
        /// 返回结果
        /// </summary>
        public bool Result { get; set; }
        /// <summary>
        /// 返回消息
        /// </summary>
        public string Message { get; set; }
        /// <summary>
        /// 待处理的SQL
        /// </summary>
        public ArrayList SqlList { get; set; }
        /// <summary>
        /// 待处理的排产明细ID
        /// </summary>
        public string ApsPlanDetailIDs { get; set; }
        /// <summary>
        /// 是否存在其他版本工序排产
        /// </summary>
        public bool IsOtherRev { get; set; }
    }
    /// <summary>
    /// 转工计划接收--导出
    /// </summary>
    /// <param name="context"></param>
    private void exportReceive(HttpContext context)
    {
        Dictionary<string, string> dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["params"].ToString());
        if (!string.IsNullOrWhiteSpace(dic["ScanContainerName"]))
        {
            dic["ScanContainerName"] = commonBusiness.ContainerScan(dic["ScanContainerName"]);
        }
        if (!string.IsNullOrWhiteSpace(dic["PlanStartDate"]))
        {
            dic["PlanStartDate"] = dic["PlanStartDate"] + " 00:00:00";
        }
        if (!string.IsNullOrWhiteSpace(dic["PlanEndDate"]))
        {
            dic["PlanEndDate"] = dic["PlanEndDate"] + " 23:59:59";
        }
        dic.Add("FactoryID", m_UserInfo.FactoryID);
        dic.Add("isPage", "false");
        uMESProcessResult result = apsPlanConfirm.GetApsPlanShipReceivedDatas(dic);
        DataTable dt = result.DBTable;
        DataTable dtExport = dt.AsDataView().ToTable(false, "MFGORDERNAME", "CONTAINERNAME", "PRODUCTDESCRIPTION", "WORKFLOWINFO", "NOWWORKFLOWSTEPNAME", "WORKFLOWSTEPNAME", "APSQTY", "MAINFACTORYNAME", "ASSISFACTORYNAME", "CONTAINERTYPENAME", "APSTYPENAME", "CREATEDATE", "STARTTIME", "ENDTIME", "CONFIRMEMP", "CONFIRMDATE",
            "SHIPRECPLANSTARTDATE", "SHIPRECPLANENDDATE", "RECEIVEEMP", "SHIPRECEIVEDATE", "STATUSNAME");//只保留需导出的列
        if (dtExport.Rows.Count == 0) { return; }
        dtExport.Columns["MFGORDERNAME"].ColumnName = "订单号";
        dtExport.Columns["CONTAINERNAME"].ColumnName = "批次号";
        dtExport.Columns["PRODUCTDESCRIPTION"].ColumnName = "零件名称";
        dtExport.Columns["WORKFLOWINFO"].ColumnName = "工艺版次";
        dtExport.Columns["NOWWORKFLOWSTEPNAME"].ColumnName = "当前序";
        dtExport.Columns["WORKFLOWSTEPNAME"].ColumnName = "转工序";
        dtExport.Columns["APSQTY"].ColumnName = "计划数";
        dtExport.Columns["MAINFACTORYNAME"].ColumnName = "主制工厂";
        dtExport.Columns["ASSISFACTORYNAME"].ColumnName = "承制工厂";
        dtExport.Columns["CONTAINERTYPENAME"].ColumnName = "批次类型";
        dtExport.Columns["APSTYPENAME"].ColumnName = "排产策略";
        dtExport.Columns["CREATEDATE"].ColumnName = "计划生成时间";
        dtExport.Columns["STARTTIME"].ColumnName = "计划开始时间";
        dtExport.Columns["ENDTIME"].ColumnName = "计划结束时间";
        dtExport.Columns["CONFIRMEMP"].ColumnName = "转出人";
        dtExport.Columns["CONFIRMDATE"].ColumnName = "转出时间";
        dtExport.Columns["SHIPRECPLANSTARTDATE"].ColumnName = "反馈开始时间";
        dtExport.Columns["SHIPRECPLANENDDATE"].ColumnName = "反馈结束时间";
        dtExport.Columns["RECEIVEEMP"].ColumnName = "接收人";
        dtExport.Columns["SHIPRECEIVEDATE"].ColumnName = "接收时间";
        dtExport.Columns["STATUSNAME"].ColumnName = "确认状态";

        byte[] bytes = uLMS_CommonFunction.DataTableExportToExcel(dtExport, "转工计划接收");
        context.Response.Clear();
        context.Response.Buffer = true;
        context.Response.ClearHeaders();
        context.Response.ClearContent();
        context.Response.ContentType = "application/vnd.ms-excel";
        context.Response.AddHeader("fileDownload", "1");
        context.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}{1}.xls", context.Server.UrlEncode("转工计划接收"), DateTime.Now.ToString("yyyyMMddHHmmssffff")));
        context.Response.AddHeader("Content-Length", bytes.Length.ToString());
        context.Response.AddHeader("Content-Type", "UTF-8");
        context.Response.Charset = "UTF-8";
        context.Response.ContentEncoding = System.Text.Encoding.UTF8;
        context.Response.BinaryWrite(bytes);
        context.Response.Flush();
        context.Response.Close();
    }
}